﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace Trackr.ProviderFactory
{
	public class DataProviderManager<T> where T : class
	{
		private static DataProvider<T> defaultProvider;
		private static DataProviderCollection<T> providers;

		static DataProviderManager()
		{
			Initialize();
		}

		private static void Initialize()
		{
			DataProviderConfiguration configuration = (DataProviderConfiguration)ConfigurationManager.GetSection("TrackrProvider");

			if (configuration == null)
				throw new ConfigurationErrorsException("TrackrProviders configuration section is not set correctly.");

			providers = new DataProviderCollection<T>();

			foreach (ProviderSettings provider in configuration.Providers)
			{
				var type = Type.GetType(provider.Type);
				var obj = Activator.CreateInstance(type) as DataProvider<T>;
				//obj.Initialize(obj.Name, ConfigurationManager.AppSettings);
				obj.Initialize(obj.Name, provider.Parameters);
				providers.Add(obj);
			}
			providers.SetReadOnly();

			defaultProvider = providers[configuration.Default] as DataProvider<T>;

			if (defaultProvider == null)
				throw new Exception("defaultProvider can't be set or can't be found");
		}

		public static DataProvider<T> Current
		{
			get
			{
				return defaultProvider;
			}
		}

		public static DataProviderCollection<T> Providers
		{
			get
			{
				return providers;
			}
		}
	}
}
